import { createSlice,createAsyncThunk } from "@reduxjs/toolkit";
import { getFoodApi } from "../../services/axios";
import type { FoodItem,ListItem } from "../../services/axios";




interface FoodState {
    foodList:FoodItem[]
    selected:ListItem[]
}

const initialState:FoodState = {
    foodList:[],
    selected:[]
}


export const getFood = createAsyncThunk('food/getFood', async() => {
    const res = await getFoodApi()
    return res.data
})



const foodSlice = createSlice({
    name:'food',
    initialState,
    reducers:{
        changeChecked(state,action) {
            // console.log(state.foodList)
            // console.log(action.payload)
            state.foodList.forEach(item => {
                item.list.forEach(food =>{
                    // 根据传入的name去foodlist中查找
                    if(food.name === action.payload) {
                        food.isChecked = !food.isChecked
                        if(food.isChecked) {
                            state.selected.push(food)
                        }else {
                            // 删除
                            state.selected = state.selected.filter(v=>v.name !== food.name)
                        }
                    }
                })
            })
        }
    },
    extraReducers:builder => {
        builder
            .addCase(getFood.fulfilled,(state,action) => {
                console.log(action.payload.value)
                state.foodList = action.payload.value
            })
    }
        
            

})

export const { changeChecked } = foodSlice.actions
export default foodSlice.reducer